import { memo, useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Empty, Button, Input, Select } from 'antd';
import { ArrowLeftOutlined, SearchOutlined, FilterOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import type { Article } from '@/types';
import { getMockAllArticles } from '@/Utils/localForage';
import { ArticleList } from '@/components/ArticleList';

const { Search } = Input;
const { Option } = Select;

interface SearchResultItem extends Article {
  matchScore: number;
}

const SearchResult = memo(() => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [keyword, setKeyword] = useState<string>();
  const [articles, setArticles] = useState<Article[]>([]);
  const [searchResults, setSearchResults] = useState<SearchResultItem[]>([]);
  const [filteredResults, setFilteredResults] = useState<SearchResultItem[]>([]);
  const [searchInput, setSearchInput] = useState(keyword);
  const [categoryFilter, setCategoryFilter] = useState<string>('all');
  const [difficultyFilter, setDifficultyFilter] = useState<string>('all');

  // 加载文章数据
  useEffect(() => {
    const loadArticles = async () => {
      try {
        const articlesData = await getMockAllArticles();
        if (articlesData) {
          setArticles(articlesData);
        }
      } catch (error) {
        console.error('加载文章数据失败:', error);
      }
    };
    loadArticles();
  }, []);
  // 执行搜索
  useEffect(() => {
    // 获取参数
    const searchKeyword = searchParams.get("q") || "";
    setKeyword(searchKeyword);
    setSearchInput(searchKeyword);
    if (searchKeyword) {
      performSearch(searchKeyword);
    } else {
      setSearchResults([]);
      setFilteredResults([]);
    }
  }, [searchParams, articles]);
  // 搜索功能
  const performSearch = (searchKeyword: string) => {
    if (!searchKeyword.trim()) {
      setSearchResults([]);
      setFilteredResults([]);
      return;
    }
    const results: SearchResultItem[] = [];
    const keywordLower = searchKeyword.toLowerCase();

    articles.forEach(article => {
      let matchScore = 0;
      // 标题匹配
      if (article.title.toLowerCase().includes(keywordLower)) {
        matchScore += 100;
      }
      // 摘要匹配
      if (article.summary.toLowerCase().includes(keywordLower)) {
        matchScore += 50;
      }
      // 作者匹配
      if (article.author.username.toLowerCase().includes(keywordLower)) {
        matchScore += 30;
      }

      if (matchScore > 0) {
        results.push({
          ...article,
          matchScore
        });
      }
    });

    // 按匹配分数排序
    results.sort((a, b) => b.matchScore - a.matchScore);
    setSearchResults(results);
    setFilteredResults(results);
  };



  // 处理搜索提交
  const handleSearchSubmit = (value: string) => {
    if (value.trim()) {
      setSearchParams({ q: value.trim() });
    }
  };

  // 筛选
  useEffect(() => {
    let filtered = [...searchResults];

    // 分类筛选
    if (categoryFilter !== 'all') {
      filtered = filtered.filter(item => item.category === categoryFilter);
    }

    // 难度筛选
    if (difficultyFilter !== 'all') {
      filtered = filtered.filter(item => item.difficulty === difficultyFilter);
    }

    setFilteredResults(filtered);
  }, [searchResults, categoryFilter, difficultyFilter]);


  return (
    <div className="max-w-6xl mx-auto px-6 py-8">
      {/* 页面头部 */}
      <div className="mb-8">
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/')}
          className="mb-4 bg-white rounded-lg shadow-lg p-4"
        >
          返回首页
        </Button>

        {/* 搜索框 */}
        <div className="mb-6 mx-20">
          <Search
            placeholder="搜索文章、作者、标签..."
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            onSearch={handleSearchSubmit}
            enterButton={<SearchOutlined />}
            size='large'
          />
        </div>

        {/* 搜索结果统计 */}
        {keyword && (
          <div className="text-gray-600 mb-4">
            找到 {filteredResults.length} 个相关结果
            {filteredResults.length !== searchResults.length && (
              <span className="text-gray-400 ml-2">
                (已筛选，共 {searchResults.length} 个)
              </span>
            )}
          </div>
        )}
      </div>

      {/* 筛选和排序 */}
      {searchResults.length > 0 && (
        <div className="mb-6 p-4 bg-white rounded-lg">
          <div className="flex items-center gap-4 flex-wrap">
            <div className="flex items-center gap-2">
              <FilterOutlined className="text-gray-500" />
              <span className="text-sm text-gray-600">筛选:</span>
            </div>

            <Select
              value={categoryFilter}
              onChange={setCategoryFilter}
              style={{ width: 120 }}
              size="small"
            >
              <Option value="all">全部分类</Option>
              <Option value="teach">教程</Option>
              <Option value="share">分享</Option>
              <Option value="question">问答</Option>
              <Option value="other">其他</Option>
            </Select>

            <Select
              value={difficultyFilter}
              onChange={setDifficultyFilter}
              style={{ width: 120 }}
              size="small"
            >
              <Option value="all">全部难度</Option>
              <Option value="easy">入门</Option>
              <Option value="medium">进阶</Option>
              <Option value="hard">高级</Option>
            </Select>
          </div>
        </div>
      )}

      {/* 搜索结果列表 */}
      <AnimatePresence mode="wait">
        {filteredResults.length > 0 ? (
          <motion.div
            className='bg-white rounded-lg shadow-lg p-4'
          >
            <ArticleList articles={filteredResults} />
          </motion.div>

        ) : keyword ? (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="py-12"
          >
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <div className="text-center">
                  <p className="text-gray-500 mb-2">未找到相关结果</p>
                  <p className="text-sm text-gray-400">
                    尝试使用不同的关键词或调整筛选条件
                  </p>
                </div>
              }
            />
          </motion.div>
        ) : (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="py-12"
          >
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description="请输入搜索关键词"
            />
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
});

SearchResult.displayName = "SearchResult";

export default SearchResult;